let tBizType = require("../../utils/bizTypeData.js");
let tcity = require("../../utils/cityData.js");
const utils = require("../../utils/util.js");
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //默认城市
    locationCity: app.globalData.defaultCity, 
    //tab切换
    tabIsActive: '0',
    //是否隐藏遮罩
    isHiddenMask: true,
    //是否隐藏‘全文’文字
    isHiddenMore: false,
    //是否显示更多
    isMore: false,
    //是否显示隐藏评论
    isHiddenDiscuss: true,
    //是否有点赞或者评论
    isDiscuss: true,
    
    //是否隐藏发单接单
    isHiddenAdd: true,
    //发单按钮默认层级高
    isHighZindex:true,
    // 类别
    typeList: [
      { "text": "全部", "value": 0 }, { "text": "发单动态", "value": 1 }, { "text": "接单动态", "value": 2 }],
    // 类别默认选择
    filterTypeIsActive: '0',
    //业务
    bizTypeGroups: [],
    bizTypes: [],
    //业务选择第一列默认选择项
    filterServerOne: '0',
    //业务选择第一列默认选择项
    filterServerTwo: '0',
    //是否隐藏条件筛选的列表
    filterIsHidden: true,
    //初始化的时候tab默认的层级为100
    tabZindex:'200',
    //初始化的时候发单按钮的层级默认为100
    addZindex:'200',
    //评论输入框是否隐藏
    discussInputHidden: true,
  //类别显示
   postTypeName:'类别',
   //业务显示 
   bizTypeName:'业务',
   //地区显示 
   locationName:'地区',
   /*城市选择所需数据字段 */
   provinces: [],
   citys: [],
   allcity:[],
   //选中省
   provinceActive:0,
   //选中市
   cityActive:0,
   //分页
   pageIndex:1,
   //每页数量
   pageSize:5,
   //车圈动态
   dataList:[],
   //总数量
   total:0,
   //更多
   hasMore:false,
   //评论要提交的数据
   comPostType:0,
   comPostId:0,
   comOwnerShopId:0,
   inputTxt:'',
   comIndex:0,
   bizTypeGroupId:0,
   selProvinceId:0,
   commentInputFocus:false,
   isOnShow:false,
   noData:false,//是否有动态数据
   isAllCity:false,//是否点击全部城市
   cityIndex:1,//取全部城市的页码
   tipText:'',
   forbidScroll:false
  },
  //跳转到城市列表页面
  goToCityList: function () {
    wx.navigateTo({
      url: "../index/citylist/citylist"
    })
  },
  
  //打电话
  callPhone: function (e) {
    var that = this;

    utils.safeDoAction(function () {
      var index = e.currentTarget.dataset.index;
      var dataList = that.data.dataList;
      var oInfo = dataList[index];
      that.setData({
        isOnShow: true
      });
      utils.postData(
        utils.apiUrl + "/message/AddPhoneCall",
        {
          OwnerShopID: oInfo.ShopID,
          PostType: oInfo.PostType,
          PostId: oInfo.PostID,
          CommentUserID: utils.getUserId(),
          FromType: 1
        },
        function () {
          wx.makePhoneCall({
            phoneNumber: oInfo.Mobile
          });
        }
      );
    });    
  },
  //评论点击切换
  discussTap: function (e) {
    var that = this;
    utils.safeDoAction(function () {
    var index = e.currentTarget.dataset.index;
    var dataList = that.data.dataList;
    var isShowHid = dataList[index].showCommentBtn;
    //创建动画实例
    var animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    dataList.forEach((item, index) => {
      animation.width(0).step();//step方法可以使动画分步
      item.animationData = animation.export();//export方法将动画数据传递给标签组件上的animation属性
      item.showCommentBtn = false;
    });
    if (isShowHid == true) {
      animation.width("300rpx").step();
      dataList[index].animationData = animation.export();
      dataList[index].showCommentBtn = false;
      that.setData({
        dataList: dataList,
        discussInputHidden: true
      });
      setTimeout(function () {
        animation.width("0rpx").step()
        dataList[index].animationData = animation.export();
        this.setData({
          dataList: dataList
        })
      }.bind(that), 200);    
    } else {
      dataList[index].showCommentBtn = true;
      animation.width(0).step();
      dataList[index].animationData = animation.export();
      that.setData({
        dataList: dataList,
        discussInputHidden: true
      });
      setTimeout(function () {
        animation.width("300rpx").step()
        dataList[index].animationData = animation.export();
        this.setData({
          dataList: dataList
        })
      }.bind(that), 200);
    }
    that.setData({
      dataList: dataList,
      discussInputHidden: true
    })
    });
  },
//  点击空白处关闭评论
  bindMainTap: function () {
    var that = this;
    var dataList = that.data.dataList;
    var animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    dataList.forEach((item, index) => {
      animation.width(0).step();
      item.animationData = animation.export();
      item.showCommentBtn = false;
    });
    that.setData({
      dataList: dataList,
      discussInputHidden: true,
      commentInputFocus: false
    });
  },
  //发表动态
  addTap: function () {
    this.setData({
      isHiddenAdd: !this.data.isHiddenAdd,
      isHiddenMask: !this.data.isHiddenMask,
      tabZindex:'120',
      addZindex: '200',
      forbidScroll:true
    })
  },
  // tab选择
  typeTap: function (e) {
    this.setData({
      tabIsActive: e.currentTarget.dataset.idx,
      filterIsHidden: false,
      isHiddenMask: false,
      isHighZindex:false,
      addZindex:'120',
      tabZindex: '200',
      inputTxt:'',
       tipText: '',
       forbidScroll:true
    })
  },
  //类别中的选择
  filterTypeTap: function (e) {
    var that = this;
    var typeid = e.currentTarget.dataset.val;
    var typeList = that.data.typeList;
    var typeName = "";
    for (let i = 0; i < typeList.length;i++)
    {
      if (typeid == typeList[i].value)
      {
        typeName = typeList[i].text;
      }
    }
    if (typeid==0)
    {
      typeName='类别'
    }
    this.setData({
      postTypeName: typeName,
      filterTypeIsActive: typeid,
      filterIsHidden:true,
      isHiddenMask:true,
      forbidScroll:false,
      pageIndex: 1,
      dataList: []
    });
    that.getData();
  },

  //业务第一列选择
  filterServerOneTap: function (e) {
    var that = this;
    let bizTypesli = [];
    var groupId = e.currentTarget.dataset.val;
    var groupList = that.data.bizTypeGroups;
    var groupName = "";
    for (let i = 0; i < groupList.length; i++) {
      if (groupId==0)
      {
        if(i>0)
        {
          for (var j in groupList[i].childs) {
            if (groupList[i].childs[j].value != 0) {
              bizTypesli.push(groupList[i].childs[j]);
            }
          }
        }
       
      }else if (groupId == groupList[i].value) {
        bizTypesli = groupList[i].childs;
      }
    }
    if (bizTypesli[0].value!=0)
    {
      bizTypesli.unshift({ "text": "全部", "value": 0 });
    }
    this.setData({
      filterServerOne: groupId,
      bizTypes: bizTypesli,
      filterServerTwo: '0',
      bizTypeGroupId: groupId
    })
  },
  //业务第二列选择
  filterServerTwoTap: function (e) {
    var that = this;
    var bizTypeId = e.currentTarget.dataset.val;
    var bizTypeList = that.data.bizTypes;
    var bizTypeNameli = "";
    var index = e.currentTarget.dataset.index;
    if(bizTypeId==0) 
    {
      that.getParentName();
    }else{
      bizTypeNameli = bizTypeList[index].text;
      this.setData({
        bizTypeName: bizTypeNameli
      });
  }
    this.setData({
      filterServerTwo: bizTypeId,
      filterIsHidden: true,
      isHiddenMask: true,
      forbidScroll:false,
      pageIndex: 1,
      dataList:[]
    });
   that.getData();
  },
  /**
   * --收发单按钮
   */
  closeMask:function(){
    this.setData({
      filterIsHidden: true,
      isHiddenMask: true,
      isHiddenAdd:true,
      forbidScroll: false
    })
  },
  /**
   * 点评论显示输入框，隐藏评论按键
   */
  discussInputTap: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var postType = dataset.posttype;
    var postId = dataset.postid;
    var ownerShopId = dataset.ownershopid;
    var comIndexli = dataset.index;
    var dataList = that.data.dataList;
    dataList[comIndexli].showCommentBtn = false;
    var animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    animation.width(0).step();
    dataList[comIndexli].animationData = animation.export();
    this.setData({
      dataList: dataList,
      discussInputHidden:false,
      comPostType: postType,
      comPostId: postId,
      comOwnerShopId: ownerShopId,
      comIndex: comIndexli,
      commentInputFocus: true,
      isHiddenDiscuss:true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    tBizType.init(that);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    var citys = tcity.cityList(0);
     that.setData({ 
       'provinces': tcity.provinceList(),
       'citys': citys,
    })
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (that.data.isOnShow) {
      this.setData({
        isOnShow: false
      });
      return;
    }

    var biztypeid = app.globalData.bizTypeId;
    var bizTypeData = that.data.bizTypeData;
    var bizTypeName = '';

    const bizTypeGroups = [{ "text": "全部", "value": 0 }];
    const bizTypes = [{ "text": "全部", "value": 0 }];
    for (let i = 0; i < bizTypeData.length; i++) {
      bizTypeGroups.push(bizTypeData[i]);
      for (let j = 0; j < bizTypeData[i].childs.length; j++) {
        bizTypes.push(bizTypeData[i].childs[j]);
        if (biztypeid > 0 && biztypeid == bizTypeData[i].childs[j].value) {
          bizTypeName = bizTypeData[i].childs[j].text;
        }
      }
    }
    if (bizTypeName != '') {
      that.setData({
        bizTypeName: bizTypeName,
        filterServerTwo: biztypeid,
        tabIsActive: 1
      })

    }else
    {
      that.setData({
        bizTypeName: '业务',
        filterServerTwo: 0,
        tabIsActive: 0
      })
    }
   
    that.setData({ 
      bizTypeGroups: bizTypeGroups,
      bizTypes: bizTypes,
      pageIndex: 1,
      filterTypeIsActive: 0,
      cityActive: 0,
      bizTypeGroupId: 0,
      selProvinceId: 0,
      postTypeName:'类别',
      locationName:'地区',
      filterIsHidden: true, 
      isHiddenMask: true,
      forbidScroll:false,
      isHighZindex: true,
      discussInputHidden:true,
      filterServerOne:0,
      provinceActive:0,
      citys: tcity.cityList(0),
      locationCity: app.globalData.defaultCity
    })
     that.getData();
     app.globalData.bizTypeId = 0;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      pageIndex: 1
    });
    that.getData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (!that.data.hasMore) {
      that.setData({
        tipText: "没有更多数据了" 
      });
      return;
    }
    else {
      that.setData({
        tipText: "正在加载更多数据.."
      });
    }
    if (that.data.isLoadingMore) {
      return;
    }
    that.setData({
      pageIndex: that.data.pageIndex + 1,
      isLoadingMore: true
    });
    utils.getData(
      utils.apiUrl + '/CarCircle/GetSearchListByCondition',
      {
        page: that.data.pageIndex,
        rows: that.data.pageSize,
        PostType: that.data.filterTypeIsActive,
        BizTypeID: that.data.filterServerTwo,
        LocationID: that.data.cityActive,
        GroupID: that.data.bizTypeGroupId,
        ProvinceID: that.data.selProvinceId,
        Content: ''
      },
      function (response) {
        if (response.status == 0) {
          var tempList = that.data.dataList;
          var data = response.data;
          var result = data.items;
          var total = data.total;
          var listCombine = tempList.concat(result);
          var hasMore = false;
          if (listCombine.length < total) {
            hasMore = true;
          }
          var noData = false;
          if (total==0)
          {
            noData = true;
          }
          that.setData({
            dataList: listCombine,
            isLoadingMore: false,
            hasMore: hasMore,
            noData:noData
          });
        }
      },
      function () { },
      function () {
       
        app.globalData.bizTypeId = 0;
      }
    );
  },

  /**
 * 用户点击右上角分享
 */
  onShareAppMessage: function (res) {
    if (res.from === 'menu') {
      // 来自页面右上角转发按钮
      return {
        title: '快来上车务圈，更多人脉，更多订单！限时免费注册！',
        path: '/pages/index/index',
        imageUrl: '/imgs/share-banner.jpg'
      };
    }
  },
  /**
   * 省单击事件
   */
  bindProvinceTap:function(e)
  {
    var that = this;
    var cityLi = [];
    var provinceId = e.currentTarget.dataset.val;
    var index = e.currentTarget.dataset.index;
    var provinceList = that.data.provinces;
    //var cityData = that.data.cityData;
    var isAllCity = false;
    var cityIndex = 1;
     cityLi = tcity.cityList(provinceId);

    this.setData({
      isAllCity: isAllCity,
      cityIndex: cityIndex,
      provinceActive: provinceId,
      citys: cityLi,
      selProvinceId: provinceId
    })
  },
  /**
   * 市单击事件
   */
  bindCityTap:function(e)
  {
    var that = this;
    var cityId = e.currentTarget.dataset.val;
    var index = e.currentTarget.dataset.index;
    var cityList = that.data.citys;
    var cityNameli = "";
    if(cityId==0)
    {
      that.getProvinceName();
    }else
    {
      cityNameli = cityList[index].text;
      this.setData({
        locationName: cityNameli,
      });
    }
    this.setData({
      cityActive: cityId,
      filterIsHidden: true,
      isHiddenMask: true,
      forbidScroll:false,
      pageIndex: 1,
      dataList: []
    });
    that.getData();
  },
  getData: function () {
    //console.log("start");
    var that = this;
    utils.getData(
      utils.apiUrl + '/CarCircle/GetSearchListByCondition',
      { 
        page: that.data.pageIndex,
        rows: that.data.pageSize,
        PostType: that.data.filterTypeIsActive,
        BizTypeID: that.data.filterServerTwo,
        LocationID: that.data.cityActive,
        GroupID: that.data.bizTypeGroupId,
        ProvinceID: that.data.selProvinceId,
        Content: ''
      },
      function (response) {
        if (response.status == 0) {
          //console.log("end");
          var data = response.data;
          var dataList = data.items;
          var total = data.total;
          var hasMore = false;
          if (dataList.length < total) {
            hasMore = true;
          }
          var noData = false;
          if (total == 0) {
            noData = true;
          }
          that.setData({
            dataList: dataList,
            total: total,
            hasMore: hasMore,
            noData: noData
          });
        }
      },
      function () { },
      function () {
        
      }
    );
  },
  /**
   * 评论
   */
  bindFormSubmit: function (e) {
    var that = this;
    var formData = e.detail.value;
    var cIndex = that.data.comIndex;
    if (formData.CommentContent == '') {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }
    var data = {
      OwnerShopID: that.data.comOwnerShopId,
      PostType: that.data.comPostType,
      PostId: that.data.comPostId,
      CommentUserID: utils.getUserId(),
      CommentContent: formData.CommentContent
    }
    // wx.showLoading({
    //   title: '正在提交,请等待..',
    // });
    utils.postData(
      utils.apiUrl + '/Message/AddComment',
      data,
      function (response) {
        var data = response.data;
        var obj = that.data.dataList;
        if (response.status == 0) {
          obj[cIndex].CommentInfo.push(data);
         // obj[index].showCommentBtn = false;
          that.setData({
            isHiddenDiscuss: true,
            dataList: obj,
            inputTxt: '',
            discussInputHidden:true
          })
        }
        else {
          wx.showModal({
            title: '评论失败',
            content: response.message,
            showCancel: false,
          });
        }
      },
      {},
      function () {
        //wx.hideLoading();
      }
    )
    return;
   },
  /**
   * 点赞
   */
  catchTapBtnLike: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var index = dataset.index;
    var postType = dataset.posttype;
    var postId = dataset.postid;
    var ownerShopId = dataset.ownershopid;
    var commentUserId = utils.getUserId();
    var animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    that.animation = animation;
    var data = {
      OwnerShopID: ownerShopId,
      PostType: postType,
      PostId: postId,
      CommentUserID: utils.getUserId()
    }
    // wx.showLoading({
    //   title: '正在提交,请等待..',
    // });
    utils.postData(
      utils.apiUrl + '/Message/AddLike',
      data,
      function (response) {
        var dataList = that.data.dataList;
        if (response.status == 0) {
          var data = response.data;
          dataList[index].LikeUser.push(data);
        }
        dataList.forEach((item, index) => {
          animation.width(0).step();
          item.animationData = animation.export();
          item.showCommentBtn = false;
        });
        dataList[index].showCommentBtn = false;
        that.setData({
          dataList: dataList
        })
      },
      {},
      function () {
        //wx.hideLoading();
        that.setData({
          isHiddenDiscuss: true
          
        })
      }
    )
  },
  /**   
      * 预览图片  
      */
  previewImage: function (e) {
    var that = this
    var current = e.currentTarget.dataset.img;
    var contentlistTem = that.data.dataList;
    var postid = e.currentTarget.dataset.postid;
    var postype = e.currentTarget.dataset.postype;

    var list=[];
    for (let i = 0; i < contentlistTem.length;i++)
    {
      if (contentlistTem[i].PostID == postid && contentlistTem[i].PostType == postype)
      {
        list = contentlistTem[i].PostImgList;
        break;
      }
    }
    if(list.length==0)
    {
      list.push(current);
    }   
    that.setData({
      isOnShow:true
    });
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: list // 需要预览的图片http链接列表  
    })
  },
  /**
   * 跳转到接单页面
   */
  bindReceivePost: function () {
    var that = this;
    that.setData({
      isHiddenAdd: true,
      isHiddenMask: true,
      forbidScroll: false
    });
    utils.safeOpenUrl("/pages/carcircle/addreceivepost/addreceivepost", function () {
      
    });
  },
  /**
   * 跳转到发单页面
   */
  bindSendPost: function () {
    var that = this;
    that.setData({
      isHiddenAdd: true,
      isHiddenMask: true,
      forbidScroll: false
    });
    utils.safeOpenUrl("/pages/carcircle/addsendpost/addsendpost", function () {

    });
  },
  //设置业务类型名
  getParentName:function(){
    var that = this;
    var name = '';
    var groupArr = that.data.bizTypeGroups;
    var groupId = that.data.filterServerOne;
    for (var i in groupArr)
    {
      if (groupArr[i].value == groupId) {
          name = groupArr[i].text;
          break;
        }
    }
    if(groupId==0)
    {
      name='业务'
    }
    this.setData({
      bizTypeName: name
    });
  },
  //设置省名
  getProvinceName: function () {
    var that = this;
    var name = '地区';
    var provinceArr = that.data.provinces;
    var provinceId = that.data.provinceActive;
   if (that.data.provinceActive!=0)
    {
     for (var i in provinceArr) {
       if (provinceArr[i].value == provinceId) {
         name = provinceArr[i].text;
            break;
          }
      }
    }
    this.setData({
      locationName: name
    });
  },
  /**
   * 跳转到查询页面
   */
  bindSearch: function () {
    wx.navigateTo({
      url: '/pages/search/search',
    }) 
  },
  /**
   * 跳转发布动态的店铺
   */
  bindJumpToUserShop:function(e){
    var shopid = e.currentTarget.dataset.shopid;
    var url= '/pages/carcircle/othermy/othermy?shopid='+shopid;
    utils.safeOpenUrl(url);
   },
  bindMainTap: function () {
    var that = this;
    var dataList = that.data.dataList;
    //创建动画实例
    var animation = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
    });
    dataList.forEach((item, index) => {
      animation.width(0).step();//step用来进行动画的分步
      item.animationData = animation.export();//通过export方法，将动画的数据，传递给标签组件上的animation属性
      item.showCommentBtn = false;
    });
    that.setData({
      dataList: dataList,
      discussInputHidden: true,
      commentInputFocus: false
    });
  },
   hiddenComment:function(){
    var that = this;
    that.setData({      
      discussInputHidden: true
    })
  }
}) 